# coding: utf-8
import re
import time

from host import memdb
from host.settings import ALERT_CONFIG
from util.log import logger
from util.report import report

# 抽取CPU使用率
PATTERN_CPU = r'.*Cpu\(s\):.*,\s*([\d\.]+)%?\s*id,.*'
# 抽取内存使用率
PATTERN_MEM = r'.*Mem\s*:\s*(\d+)k?\s*total.*,\s*(\d+)k?\s*free,.*'
# 抽取分区使用率
PATTERN_DISK = r'.*\s+(\d+)%\s+(\S+).*'


def extractor_performance(ip, content, gather_type):
    """
    从TOP内容中抽取CPU使用率信息，内存使用率信息
    :param ip:
    :param content:
    :param gather_type:
    :return:
    """
    cpu, mem = None, None
    for record in content.split('\n'):
        c = re.match(PATTERN_CPU, record)
        m = re.match(PATTERN_MEM, record)
        if c:
            cpu = round(100 - float(c.group(1)))
        if m:
            mem = round(100 - int(m.group(2)) * 100 / int(m.group(1)))

    logger.info("指标提取:%s,CPU%s MEM%s" % (ip, cpu, mem))

    memdb.compute_alert(
        ip,
        gather_type,
        'CPU',
        cpu,
        ALERT_CONFIG.get('CPU')[0],
        None,
        ALERT_CONFIG.get('CPU')[1]
    )
    memdb.compute_alert(
        ip,
        gather_type,
        'MEM',
        mem,
        ALERT_CONFIG.get('MEM')[0],
        None,
        ALERT_CONFIG.get('MEM')[1]
    )

    report_data_cpu = {
        'appCode': 'HOST_' + ip,
        'metricCode': 'CPU',
        'metricValue': cpu,
        'eventTime': round(time.time() * 1000)
    }

    report_data_mem = {
        'appCode': 'HOST_' + ip,
        'metricCode': 'MEM',
        'metricValue': mem,
        'eventTime': round(time.time() * 1000)
    }

    logger.info(report_data_cpu)
    logger.info(report_data_mem)

    report(report_data_cpu)
    report(report_data_mem)


def extractor_disk(ip, content, gather_type):
    """
    抽取主机各磁盘分区使用率
    :param ip: 主机地址
    :param content: 分区信息
    :param gather_type:
    :return: 各分区使用率数组[(/var,80),(/home,90)]
    """
    for record in content.split('\n'):
        m = re.match(PATTERN_DISK, record)
        if m:
            partition = m.group(2)
            used = int(m.group(1))
            logger.info("指标提取:%s,磁盘%s,%s" % (ip, partition, used))
            memdb.compute_alert(
                ip,
                gather_type,
                partition,
                used,
                ALERT_CONFIG.get('DISK')[0],
                None,
                ALERT_CONFIG.get('DISK')[1]
            )

            report_data_mem = {
                'appCode': 'HOST_' + ip,
                'metricCode': partition,
                'metricValue': used,
                'eventTime': round(time.time() * 1000)
            }

            logger.info(report_data_mem)

            report(report_data_mem)


def extractor_status(ip, value):
    """
    暂时无用
    :param ip:
    :param value:
    :return:
    """
    memdb.host_alert(ip, value)


def extractor_do_nothing(ip, content):
    """
    暂时无用
    :param ip:
    :param content:
    :return:
    """
    data_file_name = '%s_'


if __name__ == '__main__':
    pass
